package com.tanhua.app.Service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.api.MovementApi;
import com.tanhua.api.UserInfoApi;
import com.tanhua.api.VisitorsApi;
import com.tanhua.app.exception.BusinessException;
import com.tanhua.app.interceptor.UserThreadLocal;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.pojo.User;
import com.tanhua.model.pojo.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VisitorsVo;
import javafx.scene.control.Alert;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.dom4j.Visitor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class MovementService {
    @Autowired
    private OssTemplate ossTemplate;
    @DubboReference
    private MovementApi movementApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @DubboReference
    private VisitorsApi visitorsApi;

    @Autowired
    private MqMessageService mqMessageService;


    public void publishMovement(Movement movement, MultipartFile[] multipartFiles) throws IOException {
        String textContent = movement.getTextContent();
        if (StringUtils.isEmpty(textContent)) {
            throw new BusinessException(ErrorResult.contentError());
        }
        movement.setUserId(UserThreadLocal.getid());
        ArrayList<String> list = new ArrayList<>();
        for (MultipartFile multipartFile : multipartFiles) {
            String url = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
            list.add(url);
        }
        movement.setMedias(list);
        movementApi.publish(movement);

    }

    public PageResult<MovementsVo> all(Long userId, int page, int pageSize) {
        if (userId == null){
            userId=UserThreadLocal.getid();
        }
        UserInfo userInfo = userInfoApi.selectById(userId);
        PageResult<Movement> movementPage = movementApi.findPageByUserId(userId, page, pageSize);
        ArrayList<MovementsVo> list = new ArrayList<>();
        for (Movement item : movementPage.getItems()) {

            MovementsVo movementsVo = MovementsVo.init(userInfo, item);
            //4、拼接redis的key，将用户的点赞状态存入redis
            String key = Constants.MOVEMENTS_INTERACT_KEY +item.getId();
            String hashKey = Constants.MOVEMENT_LIKE_HASHKEY +UserThreadLocal.getid();
            String o =(String) redisTemplate.opsForHash().get(key, hashKey);
            if (StringUtils.isNotBlank(o)){
                movementsVo.setHasLiked(1);
            }

            //4、拼接redis的key，将用户的喜欢状态存入redis
            String key1 = Constants.MOVEMENTS_INTERACT_KEY +item.getId();
            String hashKey1 = Constants.MOVEMENT_LOVE_HASHKEY +UserThreadLocal.getid();
            String o1 =(String) redisTemplate.opsForHash().get(key1, hashKey1);
            if (StringUtils.isNotBlank(o1)){
                movementsVo.setHasLoved(1);
            }

            list.add(movementsVo);
        }
        PageResult<MovementsVo> pageResult = new PageResult<>(movementPage.getPage(), movementPage.getPagesize(), movementPage.getCounts(), list);
        return pageResult;

    }

    /**
     * 查询好友动态
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult<MovementsVo> findFriendMovements(int page, int pageSize) {
        //根据自己id，查询自己可以查看的好友动态
        List<Movement> movements = movementApi.findMovements(page, pageSize, UserThreadLocal.getid());
        if (CollUtil.isEmpty(movements)) {
            return new PageResult(page, pageSize, 0, movements);
        }
        List<Long> ids = movements.stream().map(Movement::getUserId).collect(Collectors.toList());
        List<UserInfo> userInfoList = userInfoApi.findUserinfoByIds(ids);
        ArrayList<MovementsVo> vos = new ArrayList<>();
        Map<Long, UserInfo> map = userInfoList.stream().collect(Collectors.toMap(UserInfo::getId, Function.identity()));
        for (Movement movement : movements) {
            UserInfo userInfo = map.get(movement.getUserId());
            if (userInfo != null) {
                MovementsVo vo = MovementsVo.init(userInfo, movement);
                //4、拼接redis的key，将用户的点赞状态存入redis
                String key = Constants.MOVEMENTS_INTERACT_KEY +movement.getId();
                String hashKey = Constants.MOVEMENT_LIKE_HASHKEY +UserThreadLocal.getid();
                String o =(String) redisTemplate.opsForHash().get(key, hashKey);
                if (StringUtils.isNotBlank(o)){
                    vo.setHasLiked(1);
                }

                //4、拼接redis的key，将用户的喜欢状态存入redis
                String key1 = Constants.MOVEMENTS_INTERACT_KEY +movement.getId();
                String hashKey1 = Constants.MOVEMENT_LOVE_HASHKEY +UserThreadLocal.getid();
                String o1 =(String) redisTemplate.opsForHash().get(key1, hashKey1);
                if (StringUtils.isNotBlank(o1)){
                    vo.setHasLoved(1);
                }
                vos.add(vo);
            }
        }
        return new PageResult<MovementsVo>(page, pageSize, 0, vos);

    }

    /**
     * 根据大数据提供的pid，查询推荐的动态信息
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult<MovementsVo> findRecommendMovements(int page, int pageSize) {
        String redisKey = Constants.MOVEMENTS_RECOMMEND + UserThreadLocal.getid();
        String pidString = stringRedisTemplate.opsForValue().get(redisKey);
        List<Movement> movementList = new ArrayList<>();
        if (StringUtils.isEmpty(pidString)) {
            movementList=  movementApi.radomMovements( pageSize);
        } else {
            String[] strs = pidString.split(",");
            List<Long> pids = Arrays.stream(strs).skip((page - 1) * pageSize).limit(pageSize).map(pid ->
                    Long.parseLong(pid)
            ).collect(Collectors.toList());
            movementList=movementApi.findMovementsByPids(pids);
        }
        List<Long> userIds = movementList.stream().map(Movement::getUserId).collect(Collectors.toList());
        List<UserInfo> userInfoList = userInfoApi.findUserinfoByIds(userIds);
        ArrayList<MovementsVo> vos = new ArrayList<>();
        Map<Long, UserInfo> map = userInfoList.stream().collect(Collectors.toMap(UserInfo::getId, Function.identity()));
        for (Movement movement : movementList) {

            UserInfo userInfo = map.get(movement.getUserId());
            if (userInfo != null) {
                MovementsVo vo = MovementsVo.init(userInfo, movement);
                //4、拼接redis的key，将用户的点赞状态存入redis
                String key = Constants.MOVEMENTS_INTERACT_KEY +movement.getId();
                String hashKey = Constants.MOVEMENT_LIKE_HASHKEY +UserThreadLocal.getid();
                String o =(String) redisTemplate.opsForHash().get(key, hashKey);
                if (StringUtils.isNotBlank(o)){
vo.setHasLiked(1);
                }

                //4、拼接redis的key，将用户的喜欢状态存入redis
                String key1 = Constants.MOVEMENTS_INTERACT_KEY +movement.getId();
                String hashKey1 = Constants.MOVEMENT_LOVE_HASHKEY +UserThreadLocal.getid();
                String o1 =(String) redisTemplate.opsForHash().get(key1, hashKey1);
                if (StringUtils.isNotBlank(o1)){
                    vo.setHasLoved(1);
                }
                vos.add(vo);
            }
        }
        return new PageResult<MovementsVo>(page,pageSize,0,vos);
    }
//根据动态id查询动态详细信息
    public MovementsVo findMovementsByid(String id) {
  Movement movement= movementApi.findOneByid(id);

  if (movement != null) {
      UserInfo userInfo = userInfoApi.findByid(movement.getUserId());

//      查看动态发送消息
      mqMessageService.sendLogMessage(UserThreadLocal.getid(),"0202","movemennt",id);


      MovementsVo movementsVo = MovementsVo.init(userInfo, movement);
      return movementsVo;
  }
  return null;
    }



    //    接口名称：谁看过我
//    接口路径：GET/movements/visitors
    public List<VisitorsVo> QueryVisitorsList() {
//        1.获取redis中存放的上一次查询访客时间
        String key = Constants.VISITORS_USER;
        String hashKey = UserThreadLocal.getid().toString();
        String value = (String) redisTemplate.opsForHash().get(key, hashKey);
        Long data = value==null ? null:Long.parseLong(value);

//        2.调用api查询访客数据
        List<Visitors> visitors =  visitorsApi.QueryVisitorsList(UserThreadLocal.getid(),data);
//        3.判断是否有数据,如果 为空,直接返回
        if (visitors.isEmpty()){
            return null;
        }
//        4.根据房客的ids查询访客的用户详情
        List<Long> ids = visitors.stream().map(Visitors::getVisitorUserId).collect(Collectors.toList());
        Map<Long, UserInfo> map = userInfoApi.findUserinfoByIds(ids).stream().collect(Collectors.toMap(UserInfo::getId, Function.identity()));
//        5.封装vos
        ArrayList<VisitorsVo> vos = new ArrayList<>();
        for (Visitors visitor : visitors) {
            UserInfo userInfo = map.get(visitor.getVisitorUserId());
            if (userInfo != null){
                VisitorsVo vo = VisitorsVo.init(userInfo, visitor);
                vos.add(vo);
            }

        }
//        6.返回结果
        return vos;

    }
}
